/**
 * 创建时间：2021年10月24日
 * 编辑人：魏青波
 * 创建人：魏青波
 * 标题：员工管理页面
 *
 */
import React, { useState, useRef, useEffect } from 'react';
import { Table, Space, Button, Popconfirm, message } from 'antd';
import {
  RightOutlined,
  DownOutlined,
  ReloadOutlined,
  FullscreenExitOutlined,
} from '@ant-design/icons';
import Search from './Search';
import Modal from './Modal';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import {
  getStaffList,
  updateStaffState,
  getStaffInfo,
  getStaffDepartment,
  down,
} from '@/services/staffManage';

import './index.css';

export default function UserManage() {
  // modalVisible 保存modal的状态
  const [modalVisible, setModalVisible] = useState(false);
  const [modalTitle, setModalTitle] = useState('');
  const [isFullScreen, setIsFullScreen] = useState(false);
  const [staffListData, setStaffListData] = useState([]);
  const [loading, setLoading] = useState(true);
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [searchKey, setSearchKey] = useState();
  const [id, setId] = useState();
  const [staffInfoModal, setStaffInfoModal] = useState();
  const [staffDepartmentList, setStaffDepartmentList] = useState([]);
  const [updateAid, setUpdateAid] = useState();

  //获取员工列表/状态列表
  const getStaffListData = async () => {
    const msg = await getStaffList({ searchKey, id, page, pageSize });
    setStaffListData(msg);
    setLoading(false);
  };

  //执行一次
  useEffect(() => {
    setLoading(true);
    getStaffListData();
  }, [page, pageSize, searchKey, id]);

  //新增员工
  const addStaff = async () => {
    var btnText = document.getElementById('addBtn').textContent;
    setModalTitle(btnText);
    const msg = await getStaffDepartment();
    setStaffDepartmentList(msg);
    setStaffInfoModal();
    setModalVisible(true);
  };

  // 修改员工
  const updateStaff = async (aid) => {
    const msg1 = await getStaffInfo({ aid });
    setStaffInfoModal(msg1);
    const msg2 = await getStaffDepartment({ aid });
    setStaffDepartmentList(msg2);
    var btnText = document.getElementById('updateBtn').textContent;
    setModalTitle(btnText);
    setUpdateAid(aid);
    setModalVisible(true);
  };

  //关闭modal
  const updateModalVisible = () => {
    setModalVisible(false);
  };

  //确定离职、重新入职
  const confirm = async (aid) => {
    setLoading(true);
    await updateStaffState({ aid: aid });
    getStaffListData();
  };

  //取消离职、重新入职
  function cancel() {
    message.error('Click on No');
  }

  // 刷新表格
  const Refresh = () => {
    setSearchKey();
    setId();
    setPage(1);
    setLoading(true);
    getStaffListData();
  };

  //改变page和pageSize的回调
  const pageChange = (a, b) => {
    setPage(a);
    setPageSize(b);
  };

  //搜索员工
  const searchHandle = (values) => {
    setSearchKey(values.searchKey);
    setId(values.id);
    setPage(1);
    setPageSize(10);
  };

  //table全屏展示
  const fullScreen = () => {
    var dom = document.getElementById('div1'); //绑定想要全屏的组件
    if (!isFullScreen) {
      dom.webkitRequestFullScreen(); //进入全屏
      setIsFullScreen(!isFullScreen);
    } else {
      dom = document;
      dom.webkitCancelFullScreen(); //退出全屏
      setIsFullScreen(!isFullScreen);
    }
  };

  const changeColor0 = useRef();
  const changeColor1 = useRef();
  const mouseMoveColor = (changeColor) => {
    return () => {
      var dom = document.getElementById(changeColor.current.id);
      dom.style.color = '#1890FF';
    };
  };
  const mouseLeaveColor = (changeColor) => {
    return () => {
      var dom = document.getElementById(changeColor.current.id);
      dom.style.color = 'black';
    };
  };

  //下载附件
  const downFile = async (enclosureId) => {
    await down({ enclosureId });
  };

  // 设置table的行
  const columns = [
    {
      title: '工号',
      dataIndex: 'jobNumber',
      key: 'staffNumber',
    },
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      key: 'phone',
    },
    {
      title: '性别',
      dataIndex: 'sex',
      key: 'sex',
      render: (text) => {
        if (text) {
          return <span>男</span>;
        } else {
          return <span>女</span>;
        }
      },
    },
    {
      title: '状态',
      dataIndex: 'stateName',
      key: 'stateName',
      render: (text) => {
        var stateColor = 'rgba(82, 196, 26, 1)';
        if (text === '离职') {
          stateColor = 'rgba(217, 217, 217, 1)';
        }
        return (
          <div id="state">
            <div id="staffState" style={{ backgroundColor: stateColor }} />{' '}
            <div id="text">{text}</div>
          </div>
        );
      },
    },
    {
      title: '所属部门',
      dataIndex: 'departmentName',
      key: 'departmentName',
      render: (text) => {
        return <span>{text}</span>;
      },
    },
    {
      title: '附件',
      dataIndex: 'file',
      key: 'file',
      render: (text, record) => {
        var disabled = false;
        var isOnClick = '';
        if (!record.enclosureId) {
          disabled = true;
          isOnClick = 'none';
        }
        return (
          <a
            disabled={disabled}
            onClick={() => {
              downFile(record.enclosureId);
            }}
            style={{ textDecoration: 'underline', pointerEvents: isOnClick }}
          >
            {record.enclosureId ? '下载附件' : '无文件'}
          </a>
        );
      },
    },
    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
      render: (text, record) => {
        var disabled0 = false;
        var disabled1 = false;
        var isOnClick0 = '';
        var isOnClick1 = '';
        if (record.stateName == '离职') {
          disabled0 = true;
          isOnClick0 = 'none';
        } else {
          disabled1 = true;
          isOnClick1 = 'none';
        }
        return (
          <Space>
            <a id="updateBtn" onClick={() => updateStaff(record.aid)}>
              修改
            </a>
            <Popconfirm
              title="你确定要离职吗？？"
              okText="确定"
              cancelText="取消"
              onConfirm={() => {
                confirm(record.aid);
              }}
              onCancel={cancel}
            >
              <a id="loseWork" disabled={disabled0} style={{ pointerEvents: isOnClick0 }}>
                离职
              </a>
            </Popconfirm>
            <Popconfirm
              title="你确定要重新入职吗？？"
              okText="确定"
              cancelText="取消"
              onConfirm={() => confirm(record.aid)}
              onCancel={cancel}
            >
              <a disabled={disabled1} style={{ pointerEvents: isOnClick1 }}>
                重新入职
              </a>
            </Popconfirm>
          </Space>
        );
      },
    },
  ];

  return (
    <PageHeaderWrapper>
      <Search searchHandle={searchHandle} Refresh={Refresh} />
      <div id="div1">
        <div id="tableHead">
          <div id="div2">
            <span id="title" key="1">
              员工列表
            </span>
          </div>
          <div id="btns">
            <Button id="addBtn" type="primary" onClick={addStaff}>
              新增
            </Button>
            <ReloadOutlined
              ref={changeColor0}
              id="btnReload"
              onMouseMove={mouseMoveColor(changeColor0)}
              onMouseOut={mouseLeaveColor(changeColor0)}
              onClick={Refresh}
            />
            <FullscreenExitOutlined
              ref={changeColor1}
              id="fullScreen"
              onMouseMove={mouseMoveColor(changeColor1)}
              onMouseOut={mouseLeaveColor(changeColor1)}
              onClick={fullScreen}
            />
          </div>
        </div>

        <Table
          dataSource={staffListData.list || []}
          rowKey="aid"
          columns={columns}
          pagination={{
            total: staffListData.rowNumber || 0,
            pageSize: pageSize,
            current: page,
            hideOnSinglePage: true,
            showSizeChanger: true,
            pageSizeOptions: [1, 2, 3, 4, 5, 10],
            onChange: pageChange,
          }}
          loading={loading}
          expandable={{
            expandIcon: ({ expanded, onExpand, record }) =>
              record.children ? (
                expanded ? (
                  <DownOutlined onClick={(e) => onExpand(record, e)} />
                ) : (
                  <RightOutlined onClick={(e) => onExpand(record, e)} />
                )
              ) : (
                <span style={{ paddingLeft: '13px' }} />
              ),
          }}
        />
        {/* rowKey='aid'  设置每一行的key */}
      </div>

      <Modal
        modalVisible={modalVisible}
        updateModalVisible={updateModalVisible}
        modalTitle={modalTitle}
        staffInfoModal={staffInfoModal}
        staffDepartmentList={staffDepartmentList}
        Refresh={Refresh}
        updateAid={updateAid}
      />
    </PageHeaderWrapper>
  );
}
